﻿using Autofac;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Mysoft.Common.Configuration;
using Mysoft.Data;
using Mysoft.Data.CacheManager.IService;
using Mysoft.Data.CacheManager.Service;
using Mysoft.Data.Repository;
using Mysoft.Domain.Basic;
using System.Reflection;

namespace Mysoft.AppStartup.Startup
{
    /// <summary>
    /// IServiceCollection扩展
    /// </summary>
    public static class AutofacContainerModuleExtension
    {
        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        public static IServiceCollection AddModuleAutofac(this IServiceCollection services, ContainerBuilder builder, IConfiguration configuration)
        {
            AddRepository(builder);
            AddDomain(builder);
            AddDomainService(builder);
            AddCacheService(builder);
            return services;
        }

        //注册仓储
        private static void AddRepository(ContainerBuilder builder)
        {
            builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).SingleInstance();
            builder.RegisterGeneric(typeof(EntityService<>)).SingleInstance();
        }
        //注册domain
        private static void AddDomain(ContainerBuilder builder)
        {
            //非泛型注册 此处指继承了DomainBase的类
            Type baseType = typeof(DomainBase);//父类约束
            var assemblysServices = Assembly.Load("Mysoft.Domain");
            //注册程序集的方式添加依赖
            builder.RegisterAssemblyTypes(assemblysServices)
             .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract)//过滤抽象类，继承了抽象接口
             .AsSelf().AsImplementedInterfaces()
             .SingleInstance();//实例的生命周期
        }
        //注册DomainService
        private static void AddDomainService(ContainerBuilder builder)
        {
            //注册仓储泛型
            builder.RegisterGeneric(typeof(DomainService<>)).SingleInstance();
        }
        //注册缓存服务
        private static void AddCacheService(ContainerBuilder builder)
        {
            //启用Redis缓存
            if (AppSetting.UseRedis)
            {
                builder.RegisterType<RedisCacheService>().As<ICacheService>().SingleInstance();
            }
            else
            {
                builder.RegisterType<MemoryCacheService>().As<ICacheService>().SingleInstance();
            }
        }
    
   
    }
}
